package com.splant.android.smart.UILevel.Community.fragments;

import android.app.Fragment;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.github.jdsjlzx.ItemDecoration.GridItemDecoration;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.recyclerview.ProgressStyle;
import com.google.gson.Gson;
import com.loopj.android.http.RequestParams;
import com.splant.android.R;
import com.splant.android.smart.CommunicationLevel.sPlantAsyncHttpClient;
import com.splant.android.smart.CommunicationLevel.sPlantJsonHttpResponseHandler;
import com.splant.android.smart.Global;
import com.splant.android.smart.ModelLevel.AreaListBean;
import com.splant.android.smart.ModelLevel.WaterListBean;
import com.splant.android.smart.SystemDefinedLevel.Utils.System_Dimen_Util;
import com.splant.android.smart.UILevel.Community.Garden_WaterRecord_Activity;

import org.apache.http.Header;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/7/21.
 */

public class Garden_WaterList_Devices_Fragment extends Fragment implements View.OnClickListener{

    private static final int REQUEST_COUNT = 3;
    private String areaId="";

    private List<AreaListBean.Area> areaList = new ArrayList<>();
    private boolean isGetAreaId = false;

    private sPlantAsyncHttpClient sPlantClient;
    private View mView;
    private LRecyclerView lrv_waterList;
    private LRecyclerViewAdapter lRecyclerViewAdapter;
    private Garden_WaterList_Devices_Adapter garden_waterList_devices_adapter;
    private List<WaterListBean.Water> waterList = new ArrayList<>();

    private TextView tv_areaName;
    private boolean isLoadFinish;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (mView == null) {

            mView = inflater.inflate(R.layout.garden_waterlist_devices_fragment,null);
            lrv_waterList = (LRecyclerView) mView.findViewById(R.id.lrv_waterList);
            tv_areaName= (TextView) mView.findViewById(R.id.tv_areaName);

            sPlantClient = sPlantAsyncHttpClient.getInstance();

            init();

            tv_areaName.setOnClickListener(this);
        }

        if (isLoadFinish==false)
            getDatas();


        return mView;
    }
    private void init()
    {
        garden_waterList_devices_adapter = new Garden_WaterList_Devices_Adapter(getActivity());
        lRecyclerViewAdapter = new LRecyclerViewAdapter(garden_waterList_devices_adapter);

        lrv_waterList.setHasFixedSize(true);
        lrv_waterList.setLayoutManager(new GridLayoutManager(getActivity(), 1));
        lrv_waterList.setAdapter(lRecyclerViewAdapter);
        lrv_waterList.setRefreshProgressStyle(ProgressStyle.BallClipRotateMultiple);

      //  lrv_waterList.setFooterViewColor(R.color.colorAccent, R.color.garden_color2 ,android.R.color.white);
        lrv_waterList.setFooterViewHint("拼命加载中","已经全部为你呈现了","网络不给力啊，点击再试一次吧");
        lrv_waterList.setLoadingMoreProgressStyle(ProgressStyle.BallSpinFadeLoader);

        lrv_waterList.setOnRefreshListener(onRefreshListener);

        lrv_waterList.setOnLoadMoreListener(onLoadMoreListener);
    }

    public void getDatas() {

        RequestParams params = new RequestParams();
        params.put("userId", Global.user.getUserId());
        params.put("pageNo", pageNo);
        params.put("pageSize",REQUEST_COUNT);

        if (areaId.equals("") == false)
            params.put("areaId", areaId);


        sPlantClient.get(sPlantAsyncHttpClient.GETWATERDEVICES, params, new sPlantJsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                try
                {
                    if (response.getInt("succeed") == 1)
                    {
                        isLoadFinish=true;
                        Gson gson = new Gson();

                        WaterListBean waterListBean = gson.fromJson(response.toString(), WaterListBean.class);

                        if (waterListBean.getWaterList() != null)
                        waterList.addAll(waterListBean.getWaterList());

                        garden_waterList_devices_adapter.setDataList(waterList);

                        if (waterListBean.getWaterList()==null||waterListBean.getWaterList().size()<REQUEST_COUNT)
                            lrv_waterList.setNoMore(true);

                        lrv_waterList.refreshComplete(REQUEST_COUNT);
                    }
                }
                catch (Exception e)
                {
                    lrv_waterList.refreshComplete(REQUEST_COUNT);
                }
            }
            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                lrv_waterList.refreshComplete(REQUEST_COUNT);
                Toast.makeText(getActivity(), getString(R.string.system_request_error), Toast.LENGTH_SHORT).show();
            }
        });

    }

    private OnRefreshListener onRefreshListener=new OnRefreshListener() {
        @Override
        public void onRefresh() {
            pageNo=0;
            waterList.clear();
            lrv_waterList.setNoMore(false);
            getDatas();
        }
    };
    private int pageNo = 0;
    private OnLoadMoreListener onLoadMoreListener=new OnLoadMoreListener() {
        @Override
        public void onLoadMore() {
            pageNo += 1;
            lrv_waterList.setNoMore(false);
            getDatas();
        }
    };
    private void showAreaList() {
        if (isGetAreaId)
            return;
        isGetAreaId = true;

        View popupView =getActivity().getLayoutInflater().inflate(R.layout.garden_arealist_popupwindow, null);

        final ListView lv_areaList = (ListView) popupView.findViewById(R.id.lv_areaList);

        final PopupWindow window = new PopupWindow(popupView, System_Dimen_Util.dip2px(getActivity(), 200), System_Dimen_Util.dip2px(getActivity(), 400));

        window.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);

        window.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#F8F8F8")));

        window.setFocusable(true);

        window.setOutsideTouchable(true);

        window.showAsDropDown(tv_areaName, 0, 2);

        RequestParams params = new RequestParams();
        params.put("userId", Global.user.getUserId());

        lv_areaList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                window.dismiss();
                areaId = areaList.get(position).getAreaId();
                tv_areaName.setText(areaList.get(position).getAreaName());
                pageNo=0;
                waterList.clear();
                lrv_waterList.setNoMore(false);
                getDatas();

            }
        });

        sPlantClient.get(sPlantAsyncHttpClient.GETAREALIST, params, new sPlantJsonHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        try {
                            isGetAreaId = false;
                            if (response.getInt("succeed") == 1) {

                                Gson gson = new Gson();
                                AreaListBean areaListBean = gson.fromJson(response.toString(), AreaListBean.class);

                                if (areaListBean.getAreaList() != null && areaListBean.getAreaList().size() > 0) {

                                    areaList.clear();
                                    AreaListBean.Area areaAll = new AreaListBean.Area();
                                    areaAll.setAreaId("");
                                    areaAll.setAreaName("全部区域");

                                    areaList.add(areaAll);
                                    areaList.addAll(areaListBean.getAreaList());

                                    Garden_AreaList_Adapter garden_areaList_adapter = new Garden_AreaList_Adapter(getActivity(), areaList);

                                    lv_areaList.setAdapter(garden_areaList_adapter);
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                        isGetAreaId = false;
                        Toast.makeText(getActivity(), getString(R.string.system_request_error), Toast.LENGTH_SHORT).show();
                    }
                });
    }

    @Override
    public void onClick(View v) {

        switch (v.getId())
        {
            case R.id.tv_areaName:
                showAreaList();
                break;

        }
    }


}
